package com.company.ems.controller;

import com.company.ems.dao.impl.EmployeeDAOImpl;
import com.company.ems.model.Employee;
import com.company.ems.model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;

@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
    private final EmployeeDAOImpl employeeDAO = new EmployeeDAOImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        action = action == null ? "list" : action;

        switch (action) {
            case "list": // 查看员工列表
                listEmployees(req, resp);
                break;
            case "view": // 查看员工详情
                viewEmployee(req, resp);
                break;
            case "editPre": // 编辑前回显数据
                editPreEmployee(req, resp);
                break;
            case "delete": // 删除员工
                deleteEmployee(req, resp);
                break;
            default:
                listEmployees(req, resp);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String action = req.getParameter("action");
        if ("add".equals(action)) {
            addEmployee(req, resp); // 添加员工
        } else if ("update".equals(action)) {
            updateEmployee(req, resp); // 更新员工
        }
    }

    // 1. 查询所有员工，跳转到列表页
    private void listEmployees(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Employee> employees = employeeDAO.findAll();
        req.setAttribute("employees", employees);
        req.getRequestDispatcher("/employee/list.jsp").forward(req, resp);
    }

    // 2. 查看单个员工详情
    private void viewEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Employee employee = employeeDAO.findById(id);
        req.setAttribute("employee", employee);
        req.getRequestDispatcher("/employee/view.jsp").forward(req, resp);
    }

    // 3. 编辑前回显员工数据
    private void editPreEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Employee employee = employeeDAO.findById(id);
        req.setAttribute("employee", employee);
        req.getRequestDispatcher("/employee/edit.jsp").forward(req, resp);
    }

    // 4. 添加新员工
    private void addEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        // 接收表单参数
        String name = req.getParameter("name");
        String department = req.getParameter("department");
        String position = req.getParameter("position");
        BigDecimal salary = new BigDecimal(req.getParameter("salary"));
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        Date hireDate = Date.valueOf(req.getParameter("hire_date"));

        // 封装员工对象
        Employee employee = new Employee();
        employee.setName(name);
        employee.setDepartment(department);
        employee.setPosition(position);
        employee.setSalary(salary);
        employee.setEmail(email);
        employee.setPhone(phone);
        employee.setHire_date(hireDate);
        employee.setCreated_by(loginUser.getId()); // 创建人ID（当前登录用户ID）

        // 调用DAO添加数据
        employeeDAO.add(employee);

        // 重定向到员工列表页
        resp.sendRedirect(req.getContextPath() + "/EmployeeServlet?action=list");
    }

    // 5. 更新员工信息
    private void updateEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 接收表单参数（含员工ID）
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String department = req.getParameter("department");
        String position = req.getParameter("position");
        BigDecimal salary = new BigDecimal(req.getParameter("salary"));
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        Date hireDate = Date.valueOf(req.getParameter("hire_date"));

        // 封装员工对象
        Employee employee = new Employee();
        employee.setId(id);
        employee.setName(name);
        employee.setDepartment(department);
        employee.setPosition(position);
        employee.setSalary(salary);
        employee.setEmail(email);
        employee.setPhone(phone);
        employee.setHire_date(hireDate);

        // 调用DAO更新数据
        employeeDAO.update(employee);

        // 重定向到员工列表页
        resp.sendRedirect(req.getContextPath() + "/EmployeeServlet?action=list");
    }

    // 6. 删除员工
    private void deleteEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        employeeDAO.delete(id);
        resp.sendRedirect(req.getContextPath() + "/EmployeeServlet?action=list");
    }
}